package com.lv.controller;

import com.google.code.kaptcha.Producer;
import com.lv.common.AjaxResult;
import com.lv.common.untils.RedisCache;
import com.lv.common.untils.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * <p>
 *   验证码管理接口
 * </p>
 *
 * @Author: 凉薄
 * @Date: 2022/01/06/22:53
 * @Description:
 */
@RestController
public class CaptchaCon {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private Producer captchaProducer;
    @GetMapping("/getCaptcha")
    public AjaxResult getCapt(){
        String uuid = UuidUtil.getSimpleUuid();
        String text = captchaProducer.createText();
        BufferedImage image = captchaProducer.createImage(text);
        ByteArrayOutputStream os=new ByteArrayOutputStream();
        try {
            ImageIO.write(image,"jpg",os);
        } catch (Exception e) {
            return AjaxResult.error("验证码创建失败！");
        }
        redisCache.setCacheObject(uuid,text,2, TimeUnit.MINUTES);
        String s ="data:image/gif;base64,"+Base64.getEncoder().encodeToString(os.toByteArray());
        AjaxResult success = AjaxResult.success("验证码创建成功", s);
        success.put("uuid",uuid);
        return success;
    }
}
